<?php
/**
 * 模板引擎核心类
*/

namespace houze;

class View {
    /**
     * 模板引擎实例
     */
    public $powerObj;
    /**
     * 模板变量
     */
    protected $data = [];
    /**
     * 全局模板变量
     */
    protected static $var = [];

    /**
     * 初始化
    */
    public function __construct($config) {
        // 初始化模板引擎
        $this->power($config['type'], $config);
        return $this;
    }

    /**
     * 模板变量静态赋值
    */
    public function share($name, $value = '') {
        if (is_array($name)) {
            self::$var = array_merge(self::$var, $name);
        } else {
            self::$var[$name] = $value;
        }

        return $this;
    }

    /**
     * 清理模板变量
    */
    public function clear() {
        self::$var  = [];
        $this->data = [];
    }

    /**
     * 模板变量赋值
    */
    public function assign($name, $value = '') {
        if (is_array($name)) {
            $this->data = array_merge($this->data, $name);
        } else {
            $this->data[$name] = $value;
        }

        return $this;
    }

    /**
     * 模板变量清空
    */
    public function delete_assign() {
        $this->data = [];
    }

    /**
     * 设置当前模板解析的引擎
    */
    public function power($type, $config) {
        $class = "\houze\\view\driver\\".$type;
        $this->powerObj = new $class($config);
        return $this;
    }

    /**
     * 配置模板引擎
    */
    public function config($name, $value = null)
    {
        $this->powerObj->config($name, $value);

        return $this;
    }

    /**
     * 检查模板是否存在
    */
    public function exists($name) {
        return $this->powerObj->exists($name);
    }

    /**
     * 解析和获取模板内容 用于输出
    */
    public function fetch($template = '', $vars = [], $config = [], $renderContent = false) {
        // 模板变量
        $vars = array_merge(self::$var, $this->data, $vars);
        $this->data = [];
        // 页面缓存
        ob_start();
        ob_implicit_flush(0);

        // 渲染输出
        try {
            $method = $renderContent ? 'display' : 'fetch';
            $this->powerObj->$method($template, $vars, $config);
        } catch (\Exception $e) {
            ob_end_clean();
            throw $e;
        }

        // 获取并清空缓存
        $content = ob_get_clean();

        return $content;
    }

    /**
     * 渲染内容输出
    */
    public function display($content, $vars = [], $config = []) {
        return $this->fetch($content, $vars, $config, true);
    }

    /**
     * 模板变量赋值
    */
    public function __set($name, $value) {
        $this->data[$name] = $value;
    }

    /**
     * 取得模板显示变量的值
    */
    public function __get($name) {
        return $this->data[$name];
    }

    /**
     * 检测模板变量是否设置
    */
    public function __isset($name) {
        return isset($this->data[$name]);
    }
}
